/**
 * 检查数据库中的等级数量脚本
 */

const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: '43.143.253.188',
  user: 'nextjs',
  password: 'yEAiRE2jcxTyRBy5',
  database: 'nextjs',
  charset: 'utf8mb4'
};

async function checkDatabaseLevels () {
  let connection;

  try {
    console.log('🔌 连接数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');

    // 检查数据库中的等级数量
    const [countResult] = await connection.execute(
      'SELECT COUNT(*) as total FROM mount_level_experience'
    );

    console.log(`📊 数据库中的等级总数: ${countResult[0].total}`);

    // 检查等级范围
    const [rangeResult] = await connection.execute(
      'SELECT MIN(level) as min_level, MAX(level) as max_level FROM mount_level_experience'
    );

    console.log(`📊 等级范围: ${rangeResult[0].min_level} - ${rangeResult[0].max_level}`);

    // 检查是否有缺失的等级
    const [missingResult] = await connection.execute(`
            SELECT t1.level + 1 as missing_level
            FROM mount_level_experience t1
            LEFT JOIN mount_level_experience t2 ON t1.level + 1 = t2.level
            WHERE t2.level IS NULL AND t1.level < (SELECT MAX(level) FROM mount_level_experience)
            ORDER BY t1.level
        `);

    if (missingResult.length > 0) {
      console.log('❌ 缺失的等级:');
      missingResult.forEach(row => {
        console.log(`  - 等级 ${row.missing_level}`);
      });
    } else {
      console.log('✅ 没有缺失的等级');
    }

    // 显示最后几个等级的数据
    console.log('\n📊 最后10个等级的数据:');
    const [lastLevels] = await connection.execute(
      'SELECT level, experience, exp_to_next, exp_per_training, training_count, total_training FROM mount_level_experience ORDER BY level DESC LIMIT 10'
    );

    console.log('等级\t累计经验\t升级经验\t训练经验\t训练次数\t总训练次数');
    console.log('----\t--------\t--------\t--------\t--------\t----------');
    lastLevels.reverse().forEach((row) => {
      console.log(`${row.level}\t${row.experience}\t\t${row.exp_to_next}\t\t${row.exp_per_training}\t\t${row.training_count}\t\t${row.total_training}`);
    });

  } catch (error) {
    console.error('❌ 检查失败:', error.message);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 运行脚本
if (require.main === module) {
  checkDatabaseLevels().catch((error) => {
    console.error('💥 脚本执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = { checkDatabaseLevels };
